<template>
  <div class="user-edit">
    <!-- Modal -->
    <!-- :styles="{top: '50%',transform: 'translateY(-50%)','border-radius': '15px',height: '80%','overflow-y': 'auto'}" -->
    <Modal
      :title="title"
      v-model="visible"
      width="1000"
      :styles="{ top: '20px', 'border-radius': '15px' }"
      :mask-closable="type == '0'"
      scrollable="true"
      transfer
    >
      <div class="drawer-content">
        <Form
          ref="form"
          :model="form"
          :rules="ruleValidate"
          label-position="top"
        >
          <Row :gutter="32">
            <Col span="24">
              <div class="radio-group">
                <RadioGroup v-model="form.type">
                  <Radio label="1">
                    <span>参观</span>
                  </Radio>
                  <Radio label="2">
                    <span>预约</span>
                  </Radio>
                </RadioGroup>
              </div>
            </Col>
          </Row>
          <Row :gutter="32">
            <Col span="12">
              <FormItem label="场地名称：" prop="title">
                <Input placeholder="请输入场地名称" v-model="form.title" />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="场地位置：" prop="address">
                <Input placeholder="请输入场地位置" v-model="form.address" />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="场地面积：（㎡)" prop="area">
                <Input placeholder="请输入场地面积" v-model="form.area" />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="参观容纳人数：" prop="count">
                <Input placeholder="请输入参观容纳人数" v-model="form.count" />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="园区大门进出时间：（分钟）" prop="inOutDoor">
                <Input v-model="form.inOutDoor" placeholder="请填写数字" />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem
                label="添加封面图片（建议尺寸：666*322）"
                class="form-noheight"
                prop="image"
              >
                <upload-pic-input v-model="form.image"></upload-pic-input>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="32" v-if="form.type == '2'">
            <Col span="12">
              <FormItem label="起租时长：（小时）" prop="startRentHour">
                <Input
                  placeholder="请输入起租时长"
                  v-model="form.startRentHour"
                />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="租金：（元/小时）" prop="price">
                <Input placeholder="请输入租金" v-model="form.price" />
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="32">
            <Col span="24">
              <div class="add-section">
                <span class="label">可用时间段：</span>
                <div class="add-list">
                  <div
                    class="add-content"
                    v-for="(item, index) in form.timeList"
                    :key="item.id"
                  >
                    <div class="form-item">
                      <FormItem
                        :prop="'timeList.' + index + '.validStartDate'"
                        :rules="{
                          required: true,
                          message: '请输入开始时间',
                          trigger: 'blur',
                        }"
                      >
                        <Input
                          v-model="item.validStartDate"
                          placeholder="请输入开始时间（例：12:30）"
                        />
                      </FormItem>
                      <FormItem
                        :prop="'timeList.' + index + '.validEndDate'"
                        :rules="{
                          required: true,
                          message: '请输入结束时间',
                          trigger: 'blur',
                        }"
                      >
                        <Input
                          v-model="item.validEndDate"
                          placeholder="请输入结束时间（例：13:35）"
                        />
                      </FormItem>
                    </div>
                    <Button
                      type="primary"
                      v-if="index == 0"
                      @click="addTimeList"
                      ><Icon type="md-add" size="24"
                    /></Button>
                    <Button type="primary" v-else @click="subTimeList(index)"
                      ><Icon type="ios-trash-outline" size="24"
                    /></Button>
                  </div>
                </div>
              </div>
            </Col>
          </Row>
          <Row :gutter="32">
            <Col span="24">
              <FormItem
                label="添加顶部轮播图：（可以添加多张,尺寸:710*322）"
                prop="sliderList"
              >
                <uploadPicThumb v-model="form.sliderList" :multiple="true" />
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="32">
            <Col span="24">
              <FormItem label="场地介绍，建议图片尺寸：500*300" prop="description">
                <div class="cantainer">
                  <div class="avatar-uploader">
                    <Upload
                      :action="uploadFileUrl"
                      :headers="accessToken"
                      :on-success="handleSuccess"
                      :show-upload-list="false"
                    >
                      <div id="Uploadfiles"></div>
                    </Upload>
                  </div>
                  <quill-editor
                    class="editorCont"
                    v-model="form.description"
                    ref="myQuillEditor"
                    :options="editorOption"
                  >
                  </quill-editor>
                </div>
                <!-- <Input
                  placeholder="请输入场地介绍"
                  v-model="form.description"
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 5 }"
                /> -->
              </FormItem>
            </Col>
          </Row>
        </Form>
      </div>
      <div slot="footer">
        <Button
          type="primary"
          size="large"
          :loading="submitLoading"
          @click="submit"
          >保存</Button
        >
        <Button size="large" @click="visible = false">取消</Button>
      </div>
      <!-- <div class="drawer-footer br" v-show="type != '0'">
        <Button type="primary" :loading="submitLoading" @click="submit"
          >提交</Button
        >
        <Button @click="visible = false">取消</Button>
      </div> -->
    </Modal>
  </div>
</template>

<script>
import { scMeetRoomSetAdd, scSiteAdd, uploadFile } from "@/api/index";
import {
  validateUsername,
  validateMobile,
  validatePassword,
} from "@/libs/validate";
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
  ["blockquote", "code-block"], // 引用  代码块
  [{ header: 1 }, { header: 2 }], // 1、2 级标题
  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
  [{ script: "sub" }, { script: "super" }], // 上标/下标
  [{ indent: "-1" }, { indent: "+1" }], // 缩进
  // [{'direction': 'rtl'}],                         // 文本方向
  [{ size: ["small", false, "large", "huge"] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
  [{ font: [] }], // 字体种类
  [{ align: [] }], // 对齐方式
  ["clean"], // 清除文本格式
  ["link", "image", "video"], // 链接、图片、视频
];
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import departmentTreeChoose from "@/views/my-components/xboot/department-tree-choose";
import uploadPicInput from "@/views/my-components/xboot/upload-pic-input";
import uploadPicThumb from "@/views/my-components/xboot/upload-pic-thumb";
import SetPassword from "@/views/my-components/xboot/set-password";
import dict from "@/views/my-components/xboot/dict";
export default {
  name: "user",
  components: {
    departmentTreeChoose,
    uploadPicInput,
    SetPassword,
    dict,
    uploadPicThumb,
    quillEditor,
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
    },
    type: {
      type: String,
      default: "0",
    },
  },
  data() {
    return {
      accessToken: {},
      uploadFileUrl: uploadFile,
      editorOption: {
        placeholder: "请编辑相关内容",
        modules: {
          toolbar: {
            container: toolbarOptions,
            // container: "#toolbar",
            handlers: {
              image: function (value) {
                if (value) {
                  // 触发input框选择图片文件
                  // console.log("触发input框选择图片文件: ",value);
                  document
                    .querySelector(".avatar-uploader #Uploadfiles")
                    .click();
                } else {
                  this.quill.format("image", false);
                }
              },
              // video:(val)=>{
              //    console.log("video");
              // }
            },
          },
        },
      },
      visible: this.value,
      title: "",
      passColor: "",
      submitLoading: false,
      maxHeight: 510,
      form: {
        timeList: [{ id: "1", validStartDate: "", validEndDate: "" }],
        type: "1",
      },
      ruleValidate: {
        title: [{ required: true, message: "请输入场地名称", trigger: "blur" }],
        address: [
          { required: true, message: "请输入场地位置", trigger: "blur" },
        ],
        area: [{ required: true, message: "请输入场地面积", trigger: "blur" }],
        count: [
          { required: true, message: "请输入参观容纳人数", trigger: "blur" },
        ],
        image: [
          { required: true, message: "请添加封面图片", trigger: "change" },
        ],
        inOutDoor: [
          {
            required: true,
            message: "请输入园区大门进出时间",
            trigger: "blur",
          },
        ],
        sliderList: [
          {
            required: true,
            type: "array",
            message: "添加顶部轮播图",
            trigger: "change",
          },
        ],
        description: [
          { required: true, message: "请输入场地介绍", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入租金", trigger: "blur" }],
        startRentHour: [
          { required: true, message: "请输入起租时长", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    handleSuccess(res, file) {
      this.loading = false;
      if (res.success) {
        this.uploadSuccess(res.result);
      } else {
        this.$Message.error(res.message);
      }
    },
    uploadSuccess(res, fileUpDom) {
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      var _this = this;
      let quill = _this.$refs.myQuillEditor.quill;
      // 获取光标所在位置
      let length = 0;
      let Selection = quill.getSelection();
      if (Selection && Selection.index) {
        length = Selection.index;
      }
      // 如果上传成功
      console.log("res:", res);
      quill.insertEmbed(length, "image", res);
      quill.setSelection(length + 1);
    },
    init() {},
    submit() {
      this.$refs.form.validate((valid) => {
        // console.log(valid,this.type)
        // console.log(this.form)
        if (valid) {
          let apiType = "";
          if (this.type == "1") {
            //修改
            apiType = "update";
          } else if (this.type == "2") {
            //添加
            apiType = "add";
          }
          this.form.sliderImage = this.form.sliderList.join(",");
          let dateList = {};
          this.form.timeList.forEach((item, index) => {
            dateList["siteValidTimes[" + index + "].validStartDate"] =
              item.validStartDate;
            dateList["siteValidTimes[" + index + "].validEndDate"] =
              item.validEndDate;
          });
          let obj = {
            ...this.form,
            ...dateList,
          };
          scSiteAdd(apiType, obj).then((res) => {
            if (res.success) {
              this.$Message.success("操作成功");
              this.visible = false;
              this.$emit("on-submit", true);
            }
          });
        }
      });
    },
    setCurrentValue(value) {
      if (value === this.visible) {
        return;
      }
      this.$refs.form.resetFields();

      // 清空数据
      if (this.type == "1") {
        this.title = "修改场地";
        let meetRoomServesList = [];
        let obj = {
          ...this.data,
          timeList: this.data.siteValidTimes,
          sliderList: this.data.sliderImage.split(","),
        };
        this.form = obj;
      } else {
        this.title = "添加场地";
        this.form = {
          timeList: [{ id: "1", validStartDate: "", validEndDate: "" }],
          type: "1",
          sliderList: [],
        };
      }

      this.maxHeight =
        Number(document.documentElement.clientHeight - 230) + "px";
      this.visible = value;
    },
    addTimeList() {
      this.form.timeList.push({ id: Date.now() });
    },
    subTimeList(index) {
      this.form.timeList.splice(index, 1);
    },
  },
  watch: {
    value(val) {
      this.setCurrentValue(val);
    },
    visible(value) {
      this.$emit("input", value);
    },
  },
  mounted() {
    this.accessToken = {
      accessToken: this.getStore("accessToken"),
    };
    this.init();
  },
};
</script>

<style lang="less" scoped>
@import "@/styles/drawer-common.less";
.cantainer {
  background: #ffffff;
  border-radius: 5px;
  margin-top: 20px;
  padding-left: 40px;
  /deep/.editorCont {
    .ql-container strong {
      font-weight: bold !important;
    }
    .ql-container em {
      font-style: italic !important;
    }
  }
}

.quill-editor {
  height: 500px;
}

.editor-btn {
  margin: 50px auto;
  display: block;
}
.previewImg {
  display: flex;
}
.radio-group {
  display: flex;
  justify-content: center;
  padding-bottom: 20px;
}
.add-section {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  .label {
    width: 100px;
    margin-top: 6px;
  }
  .ivu-form-item,
  .add-list {
    flex: 1;
  }
}
.add-content {
  display: flex;
  // flex: 1;
  .form-item {
    display: flex;
    flex: 1;
    justify-content: space-between;
    .ivu-form-item {
      // width: 48%;
      margin-right: 20px;
    }
  }
  .ivu-form-item {
    flex: 1;
  }
  .ivu-btn {
    margin-right: 0;
  }
}
</style>

